﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using VisionCloud.Domain.Common;
using VisionCloud.Utility;

namespace VisionCloud.Web.Config
{
    /// <summary>
    /// 模型绑定 特性验证，自定义返回格式
    /// </summary>
    public class ApiBehaviorConfig
    {
        public static void Init(IServiceCollection services)
        {
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    //获取验证失败的模型字段
                    var errors = actionContext.ModelState
                                .Where(e => e.Value.Errors.Count > 0)
                                .Select(e => e.Value.Errors.First().ErrorMessage)
                                .ToList();

                    //var str = string.Join("|", errors);
                    //设置返回内容
                    var result = new ApiResult
                    {
                        Code = AjaxCode.Error,
                        //参数验证失败,请检查录入的参数格式与类型是否正确
                        Message = StartupServer.CommonLocalizer["YB0150"].Value
                    };
                    return new BadRequestObjectResult(result);
                };
            });
        }
    }
}